package dataDAOImpl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


import dataConnector.Connector;
import dataDAOInterfaces.DALException;
import dataDAOInterfaces.IRecipeCompDAO;
import dataDTO.RecipeCompDTO;

public class MySQLRecipeCompDAO implements IRecipeCompDAO {

	@Override
	public RecipeCompDTO getRecipeComp(int recipeId, int commodityId)
			throws DALException {
			ResultSet rs = Connector.doQuery("SELECT*FROM receptkomponent WHERE recept_id = " + recipeId 
					+ " AND raavare_id = " + commodityId);
			try{
				if(!rs.first())
				throw new DALException ("The recipecomponent " + recipeId+ " dont exist");
				return new RecipeCompDTO(rs.getInt(1),rs.getInt(2),rs.getDouble(3),rs.getDouble(4));
			}
			catch (SQLException e) {throw new DALException(e);}
	}

	@Override
	public List<RecipeCompDTO> getRecipeCompList(int recipeId)
			throws DALException {
		List<RecipeCompDTO> list = new ArrayList<RecipeCompDTO>();
		ResultSet rs = Connector.doQuery("SELECT*FROM receptkomponent WHERE recept_id =" + recipeId);
		try{
			while(rs.next()){
			list.add(new RecipeCompDTO(rs.getInt(1),rs.getInt(2),rs.getDouble(3),rs.getDouble(4)));
		}
		}
		catch(SQLException e){throw new DALException(e);}
		return list;
	}

	@Override
	public List<RecipeCompDTO> getRecipeCompList() throws DALException {
		List<RecipeCompDTO> list = new ArrayList<RecipeCompDTO>();
		ResultSet rs = Connector.doQuery("SELECT*FROM receptkomponent");
		try{
			while(rs.next()){
			list.add(new RecipeCompDTO(rs.getInt(1),rs.getInt(2),rs.getDouble(3),rs.getDouble(4)));
		}
		}
		catch(SQLException e){throw new DALException(e);}
		return list;
	}

	@Override
	public void createRecipeComp(RecipeCompDTO recipecomponent)
			throws DALException {
		Connector.doUpdate("INSERT INTO receptkomponent(recept_id, raavare_id, nom_netto, tolerance) VALUES" +
				"(" + recipecomponent.getRecipeId() + ",'" + recipecomponent.getCommodityId()+ "','"+
				recipecomponent.getNomNetto() + "','" + recipecomponent.getTolorance()+ "')");
	}

	@Override
	public void updateRecipeComp(RecipeCompDTO recipecomponent)
			throws DALException {
			Connector.doUpdate("UPDATE receptkomponent SET recept_id= '" + recipecomponent.getRecipeId() + 
					"', raavare_id = '" + recipecomponent.getCommodityId() + "', nom_netto = '" + recipecomponent.getNomNetto()
					+ "', tolerance = '" + recipecomponent.getTolorance() + "' WHERE recept_id = '" + recipecomponent.getRecipeId()+
					"' AND raavare_id = " +recipecomponent.getCommodityId());
	}

}
